import serial
import binascii
import time
import threading

ser = serial.Serial()


def port_open():
    ser.port = "COM7"  # 设置端口号
    ser.baudrate = 115200  # 设置波特率
    ser.bytesize = 8  # 设置数据位
    ser.stopbits = 1  # 设置停止位
    ser.parity = "N"  # 设置校验位
    ser.open()  # 打开串口,要找到对的串口号才会成功
    if (ser.isOpen()):
        print("打开串口成功")
    else:
        print("打开串口失败")


def port_close():
    ser.close()
    if (ser.isOpen()):
        print("关闭串口失败")
    else:
        print("关闭串口成功")


def send(send_data):
    if (ser.isOpen()):
        # ser.write(send_data.encode('utf-8'))  #utf-8 编码发送
        ser.write(binascii.a2b_hex(send_data))  # Hex发送
        # print(send_data)
    else:
        print("发送失败")


def send_all():
    lock = threading.Lock()
    a = f_r.read()
    b = a.split()
    # print(len(b))
    # print(b)
    for i in range(len(b)):
        lock.acquire()
        send(b[i])
        # print(i, ':', b[i])
        lock.release()
        print(i, ':', b[i])
        # time.sleep(0.001)
    f_r.close()
    print("发送结束")


def read_all():
    lock = threading.Lock()
    try:
        while True:
            lock.acquire()
            # print(ser.read().hex())

            # f_w.write(ser.read().hex() + ' ')
            f_w.write(ser.read().hex() + ' ')
            lock.release()
    except:
        print("读取结束")


if __name__ == "__main__":
    path = './test_data.txt'
    # path = './65536bit.txt'
    f_r = open(path, 'r', encoding='utf-8')
    path2 = './out.txt'
    f_w = open(path2, 'w+', encoding='utf-8')
    port_open()
    # input()
    t1 = threading.Thread(target=send_all, name='send_all')
    t2 = threading.Thread(target=read_all, name='read_all')
    t1.start()
    t2.start()
    time.sleep(5)
    f_w.close()
    port_close()
